//
//  BBDHealthQuestionsViewController.m
//  棒棒哒
//
//  Created by rimi on 15/8/3.
//  Copyright (c) 2015年 rimi. All rights reserved.
//

#import "BBDHealthQuestionsViewController.h"
#import "Config.h"
#import "CustomButton.h"
#import "AFNetworking.h"

static NSString *identifier = @"MESSAGECELL";
@interface BBDHealthQuestionsViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UIView *underView;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) UITableView *chatTableView;
@property (nonatomic, strong) NSMutableArray *messageArray;
@property (nonatomic, assign) NSInteger number;
@property (nonatomic, assign) CGRect contentRect;

@end

@implementation BBDHealthQuestionsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboarWillHiden:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initializeUserInterFace];
}

- (void)initializeDataSource {
    _messageArray = [NSMutableArray array];
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    if ([defaults objectForKey:@"data"]) {
//        [_messageArray addObject:[defaults objectForKey:@"data"]];
//    }
    
}

- (void)initializeUserInterFace {
    if (!_chatTableView) {
        _chatTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _chatTableView.delegate = self;
        _chatTableView.dataSource = self;
        _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _chatTableView.backgroundColor = [UIColor whiteColor];
        [_chatTableView registerClass:[BBDMessageTableViewCell class] forCellReuseIdentifier:identifier];
        [self.view addSubview:_chatTableView];
    }
    [_chatTableView reloadData];
    
    //发送栏背景
    if (!_underView) {
        _underView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) - 99, SCREEN_WIDTH, 50)];
        _underView.backgroundColor = [UIColor colorWithRed:247/255.0 green:249/255.0 blue:248/255.0 alpha:1.0];
        _underView.layer.borderWidth = 1;
        _underView.layer.borderColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor;
        [self.view addSubview:_underView];

    }
    
    //发送框
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, SCREEN_WIDTH - 20 - 100, _underView.bounds.size.height - 10)];
    _textField.backgroundColor = [UIColor whiteColor];
    _textField.layer.borderWidth = 1;
    _textField.layer.borderColor = [UIColor blackColor].CGColor;
    _textField.layer.cornerRadius = 5;
    _textField.delegate = self;
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_underView addSubview:_textField];
    
    //发送按钮
    _sendButton = [CustomButton buttonWithFrame:CGRectMake(_textField.bounds.size.width + 20, 5, SCREEN_WIDTH - _textField.bounds.size.width - 30, _underView.bounds.size.height - 10) Title:@"发送" BackGroudImage:nil BackGroundColor:[UIColor whiteColor] TextColor:[UIColor blueColor] CornerRadius:5 BorderWidth:1 BorderColor:[UIColor blueColor]];
    [_sendButton addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [_underView addSubview:_sendButton];
}

#pragma mark -- 加载tableView
- (void)loadRequestView {
    if (_messageArray.count >= 1) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_messageArray.count - 1 inSection:0];
        [_chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }

}

#pragma mark -- 网络请求
- (void)netRequest {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    NSDictionary *dic = @{@"key" : @"c8118dd7359a1b9f4819af6234e54c6a", @"info" : _textField.text};
    [manager GET:@"http://www.tuling123.com/openapi/api" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
        NSString *currentTime = [formatter stringFromDate:[NSDate date]];
        NSDictionary *dic = @{@"content" : responseObject[@"text"], @"type" : @"1", @"time" : currentTime};
        [_messageArray addObject:dic];
        [_chatTableView reloadData];
        [self loadRequestView];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error.localizedDescription);
    }];

}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _messageArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BBDMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    cell.timeLabel.text = _messageArray[indexPath.row][@"time"];
    cell.type =(int)[_messageArray[indexPath.row][@"type"] integerValue];
    cell.message = _messageArray[indexPath.row][@"content"];
    return cell;
}

- (void)sendMessage {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    NSDictionary *dic = @{@"content" : _textField.text, @"type" : @"0", @"time" : currentTime};
    [_messageArray addObject:dic];
    
    [self netRequest];
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGRect contentRect = [_messageArray[indexPath.row][@"content"] boundingRectWithSize:CGSizeMake(self.view.bounds.size.width * 2 / 3, DBL_MAX) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]} context:nil];
    return contentRect.size.height + 60;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

#pragma mark -- keyboard
- (void)keyboardWillShow:(NSNotification *)notification {
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] delay:0.0f options:UIViewAnimationOptionCurveEaseOut  animations:^{
        CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        _chatTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - rect.size.height);
        _underView.frame = CGRectMake(0, SCREEN_HEIGHT - rect.size.height-50, SCREEN_WIDTH, 50);
    } completion:^(BOOL finished) {
        if (_messageArray.count >= 1) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_messageArray.count - 1 inSection:0];
            [_chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }];
}

- (void)keyboarWillHiden:(NSNotification *)notification {
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
        _chatTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50);
        _underView.frame = CGRectMake(0, SCREEN_HEIGHT - 99, SCREEN_WIDTH, 50);
    }completion:^(BOOL finished) {
        if (_messageArray.count >= 1) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_messageArray.count - 1 inSection:0];
            [_chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }];
}

#pragma mark -- UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_textField resignFirstResponder];
    return YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [_textField resignFirstResponder];
}

@end
